<template>
  <view class="page">
    <u-navbar autoBack fixed placeholder bgColor="#ffffff">
      <template #left>
        <view class="navBar">
          <u-icon name="arrow-left" color="#000" size="18"></u-icon>
          <text class="nav_title">发布攻略</text>
        </view>
      </template>
    </u-navbar>
    <view class="content" :style="{ height: `calc(100% - ${navBarHeight}px)` }" >
      <view class="title">
        <u--input
          v-model="strategyTitle"
          placeholder="填写标题~"
          border="bottom"
          clearable
          :custom-style="{ height: '60px' }"
        ></u--input>
      </view>
      <view class="area">
        <u--textarea v-model="strategyDesc" :maxlength="-1" :height="140" border="none" placeholder="输入正文" ></u--textarea>
      </view>
      <view class="upload">
        <u-upload
          :fileList="fileList"
          :maxCount="1"
          @afterRead="afterRead"
          @delete="deletePic"
        >
          <view class="upload-btn">
            <u-icon name="plus" color="#C9C9C9" size="20" />
            <text>上传图片</text>
          </view>
        </u-upload>
        <view class="public-btn">
          <u-button type="primary" text="发 布" color="#0E9489" shape="circle" @click="publish"/>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {uploadImg} from "@/api/home";
import {strategyAdd} from "@/api/introduction";
import moment from "moment";

export default {
  data() {
    return {
      strategyTitle: '',
      strategyDesc: '',
      fileList: []
    };
  },
  computed: {
    navBarHeight() {
      const platform = uni.getSystemInfoSync().platform
      const statusBarHeight = uni.getSystemInfoSync().statusBarHeight
      let navHeight = 0
      if (['ios', 'devtools'].includes(platform)) {
        navHeight = 44
      } else {
        navHeight = 48
      }
      return navHeight + statusBarHeight
    },
  },
  methods: {
    afterRead({ file }) {
      console.warn('file',file)
      uploadImg({
        filePath: file.url
      }).then(res => {
        console.warn('res', res)
        const url = res.data.url
        this.fileList.splice(0, 1, {
          url
        })
      })
    },
    deletePic({ index }) {
      this.fileList.splice(index, 1)
    },
    // 发布
    async publish() {
      if ([this.strategyTitle, this.strategyDesc, this.fileList.length].some(item => !item)) {
        this.$modal.showToast('请录入完整在发布~')
        return
      }
      // 获取地址
      let address = this.getCache('city')
      if (!address) {
        uni.getLocation({
          type: 'gcj02',
          success: async (res) => {
            console.warn('res', res)
            const {latitude, longitude} = res
            // 732c6bb5cac0b4f0372c04e3415e33ed
            const location = `${longitude},${latitude}`
            const [res1, res2] = await uni.request({
              url: `https://restapi.amap.com/v3/geocode/regeo?key=732c6bb5cac0b4f0372c04e3415e33ed&location=${location}`,
            })
            if (res1 || res2) {
              const { data }  = res1 || res2
              if (data && data.regeocode && data.regeocode.addressComponent) {
                const { province } = data.regeocode.addressComponent
                address = province
              }
            }
            if (!address) address = '安徽'
            // 缓存
            const expire = 12 * 60 * 60 * 5
            this.setCache('city', address, expire)
            await this.strategyAdd(address)
          },
          fail: (err) => {
            console.error(err)
          }
        })
      } else {
        await this.strategyAdd(address)
      }
    },
    async strategyAdd(address) {
      const { code, msg } = await strategyAdd({
        address,
        title: this.strategyTitle,
        content: this.strategyDesc,
        img: this.fileList[0].url
      })
      if (code !== 200) {
        this.$modal.msgError(msg)
      } else {
        this.$modal.msgSuccess('发布成功')
        uni.navigateBack()
      }
    },
    setCache (key, value, expire = 0){
      let obj = {
        data: value, //存储的数据
        time: Date.now() / 1000, //记录存储的时间戳
        expire: expire //记录过期时间，单位秒
      }
      console.log('setCache:',value)
      uni.setStorageSync(key, JSON.stringify(obj))
    },
    getCache(key){
      let val = uni.getStorageSync(key)
      if (!val) {
        return null
      }
      val = JSON.parse(val)
      console.log('pre setCache:',val.data)
      if (val.expire && Date.now() / 1000 - val.time > val.expire) {
        uni.removeStorageSync(key)
        return null
      }
      console.log('end setCache:',val.data)
      return val.data
    }
  }

}
</script>

<style lang="scss">
.page {
  width: 100vw;
  height: 100vh;
  .navBar {
    display: flex;
    align-items: center;
    .nav_title {
      font-size: 36rpx;
      font-weight: 400;
      color: #000000;
      margin-left: 8rpx;
    }
  }
  .content {
    background-color: #F3F3F3;
    .title {
      padding: 0 20rpx;
      background-color: #fff;
    }
    .area {
      padding: 20rpx;
      background-color: #fff;
    }
    .upload {
      padding: 20rpx;
      background-color: #fff;
      .upload-btn {
        width: 210rpx;
        height: 210rpx;
        border-radius: 15rpx;
        background: #F7F7F7;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        text {
          color: #C9C9C9;
          margin-top: 20rpx;
        }
      }
    }
    .public-btn {
      width: 100%;
      padding: 34rpx;
      box-sizing: border-box;
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
    }
  }
}
</style>
